<template>
  <div class="login">
    <div class="loginDiv">
      <div class="leftIcon" />
      <el-form ref="loginForm" v-loading="formLoadIng" :model="loginForm" :rules="loginRules" class="login-form login-form-main">
        <div v-if="tenantCompanyInfo.logo" class="logo-base64">
          <img :src="tenantCompanyInfo.logo" :width="tenantCompanyInfo.width ? tenantCompanyInfo.width : 50" :height="tenantCompanyInfo.height ? tenantCompanyInfo.height : 50" style="width: auto;">
        </div>
        <div v-else class="logo" />
        <h3 v-if="tenantCompanyInfo.logo" class="title">{{ tenantCompanyInfo.name }}</h3>
        <h3 v-else class="title">{{ $t('J博士投资管理系统') }}</h3>
        <p v-if="showDevice" style="color: #333;font-size: 12px;text-align: center">当前登录存在风险，请验证设备后登录</p>
        <template v-if="isVerify">
          <Verify captcha-type="clickWord" mode="fixed" @success="verifySuccess" />
        </template>
        <template v-else>
          <el-form-item v-if="!showDevice" prop="username">
            <el-input
              v-model="loginForm.username"
              type="text"
              auto-complete="new-password"
              clearable
              :placeholder="$t('账号')"
              @change="captchaImageShow"
            >
              <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <el-form-item v-if="!showDevice" prop="password">
            <el-input
              v-model="loginForm.password"
              type="password"
              auto-complete="new-password"
              clearable
              :placeholder="$t('密码')"
            >
              <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
            </el-input>
          </el-form-item>
          <template v-if="isCode">
            <el-form-item v-if="tenant === 'true' && !showDevice" prop="tenantCode">
              <el-input
                v-model="loginForm.tenantCode"
                type="text"
                auto-complete="off"
                clearable
                :placeholder="$t('机构编号')"
                @blur="getLanguage"
                @change="captchaImageShow"
              >
                <svg-icon slot="prefix" icon-class="code" class="el-input__icon input-icon" />
              </el-input>
            </el-form-item>
          </template>
          <el-form-item v-if="loginFailNum >= 3 && !showDevice" prop="code">
            <el-input
              v-model="loginForm.code"
              auto-complete="off"
              :placeholder="$t('验证码')"
              style="width: 63%"
            >
              <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
            </el-input>
            <div class="login-code">
              <img :src="codeUrl" @click="getCode">
            </div>
          </el-form-item>
          <el-form-item v-if="showDevice">
            <el-input
              v-model="curentDevice"
              type="text"
              auto-complete="off"
              readonly
              class="input-with-select"
              @blur="getLanguage"
            >
              <el-select slot="prepend" placeholder="" @change="changeVerifyType">
                <svg-icon slot="prefix" :icon-class="verifyType === 'phone' ? 'phone' : 'email'" class="el-input__icon input-icon" />
                <el-option value="phone">
                  <svg-icon icon-class="phone" class="el-input__icon input-icon" />
                </el-option>
                <el-option value="email">
                  <svg-icon icon-class="email" class="el-input__icon input-icon" />
                </el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <el-form-item v-if="showDevice" prop="verifyCode">
            <el-input
              v-model="loginForm.verifyCode"
              type="text"
              auto-complete="off"
              style="width: calc(100% - 160px)"
              clearable
              :placeholder="$t('设备验证码')"
              @blur="getLanguage"
            >
              <svg-icon slot="prefix" icon-class="code" class="el-input__icon input-icon" />
            </el-input>
            <el-button :disabled="deviceBtnDisable" style="width: 156px" type="primary" @click="getCheckDeviceCode">{{ $t(deviceBtnTxt) }}</el-button>
          </el-form-item>
          <!-- <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox> -->
          <el-form-item style="width:100%;">
            <el-button
              :loading="loading"
              size="medium"
              type="primary"
              style="width:100%;margin-top: 10px;"
              @keyup.enter.native="handleLogin"
              @click.native.prevent="handleLogin"
            >
              <span v-if="!loading">{{ $t('登 录') }}</span>
              <span v-else>{{ $t('登 录 中') }}...</span>
            </el-button>
          </el-form-item>
          <div v-if="!showDevice" class="pswRow">
            <div class="item left">
              <el-checkbox v-model="rememberMe">{{ $t('记住密码') }}</el-checkbox>
            </div>
            <div class="item right">
              <span class="cursor" @click="toReset">{{ $t('忘记密码') }}</span> /
              <span class="cursor" @click="onRegister">{{ $t('注册') }}</span>
            </div>
          </div>
        </template>
      </el-form>
    </div>
    <!-- <a class="pub-icon" href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzU4OTgyNDA4NQ==&action=getalbum&album_id=2120720597201551370#wechat_redirect" target="_blank">
      <i class="pub" />J博士公开课及回放
    </a> -->

    <!--  底部  -->
    <div class="el-login-footer">
      <p class="links">友情链接：
        <!-- <a href="http://www.bpea.net.cn/" target="_blank">BPEA</a> |
        <a href="https://mp.weixin.qq.com/s/e9F9I8pkL_1CZvzUKlnJug" target="_blank">圆点智汇</a> |
        <a href="http://www.easydd.net" target="_blank">易尽调</a> | -->
        <a href="https://link.smyun.net/s-fund.html" target="_blank">S基金</a> |
        <a href="https://link.smyun.net/serviceAgencies.html" target="_blank">服务机构</a> |
        <a href="https://mp.weixin.qq.com/mp/appmsgalbum?__biz=MzU4OTgyNDA4NQ==&action=getalbum&album_id=2120720597201551370#wechat_redirect" target="_blank">J博士公开课</a> |
        <a href="https://mp.weixin.qq.com/mp/homepage?__biz=MzU4OTgyNDA4NQ==&hid=3&sn=a32e8d74242d2469ba198e4481532f0a" target="_blank">投资数字化汇编</a> |
        <a href="https://link.smyun.net/file/%E5%85%AC%E5%8F%B8%E6%B3%95%E6%B3%95%E5%BE%8B%E6%B3%95%E8%A7%84%E6%B1%87%E7%BC%96.pdf" target="_blank">法律汇编</a>
      </p>
      <span>Copyright © 2016-2025 {{ $t('北京安信立融科技股份有限公司') }} - Powered By {{ $t('J博士') }}V4.0</span> |
      <span class="downChrome">
        <el-tooltip class="item" effect="dark" :content="$t('点击下载')" placement="top">
          <el-link :underline="false" href="https://www.google.cn/chrome/" target="_blank">{{ $t('推荐使用Chrome浏览器') }}</el-link>
        </el-tooltip>
      </span>
    </div>
    <div class="outsideChain">
      <el-tooltip v-if="tenant === 'true'" class="item" effect="dark" :content="$t('预约咨询')" placement="left">
        <el-button type="text" icon="el-icon-service" @click="chat" />
      </el-tooltip>
      <el-tooltip v-if="lpUrl" class="item" effect="dark" :content="$t('LP门户')" placement="left">
        <el-button type="text" @click="toOpen(lpUrl);">
          <el-link :underline="false">{{ $t('LP') }}</el-link>
        </el-button>
      </el-tooltip>
      <el-tooltip v-if="gpUrl" class="item" effect="dark" :content="$t('GP门户')" placement="left">
        <el-button type="text" @click="toOpen(gpUrl);">
          <el-link :underline="false">{{ $t('GP') }}</el-link>
        </el-button>
      </el-tooltip>
      <el-tooltip v-if="dealUrl" class="item" effect="dark" :content="$t('企业填报端')" placement="left">
        <el-button type="text" @click="toOpen(dealUrl);">
          <el-link :underline="false">{{ $t('企') }}</el-link>
        </el-button>
      </el-tooltip>
      <el-tooltip v-if="jddUrl" class="item" effect="dark" :content="$t('尽调工作台')" placement="left">
        <el-button type="text" @click="toOpen(jddUrl);">
          <el-link :underline="false">{{ $t('调') }}</el-link>
        </el-button>
      </el-tooltip>
    </div>
    <contactUs ref="contactUs" />
  </div>
</template>

<script>
import { getCodeImg, getTenant, captchaImageShow, getTenantInfo, sendDeviceCode } from '@/api/login'
import Cookies from 'js-cookie'
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getLanguage } from '@/api/dev/language/sysLanguage'
import contactUs from '@/views/contactUs'
import Fingerprint from 'fingerprintjs2'
import Verify from '@/components/Verifition/Verify'
import { getConfigKey } from '@/api/system/config'

export default {
  name: 'Login',
  components: {
    contactUs,
    Verify
  },
  data() {
    return {
      lpUrl: process.env.VUE_APP_LP_URL,
      gpUrl: process.env.VUE_APP_GP_URL,
      dealUrl: process.env.VUE_APP_DEAL_URL,
      jddUrl: process.env.VUE_APP_JDD_URL,
      codeUrl: '',
      cookiePassword: '',
      // 是否多租户模式
      tenant: 'false',
      // 登录失败次数
      loginFailNum: 0,
      // 等待框
      formLoadIng: false,
      loginForm: {
        username: '',
        password: '',
        tenantCode: '',
        code: '',
        uuid: '',
        verifyCode: '',
        deviceId: ''
      },
      rememberMe: true,
      loginRules: {
        username: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ],
        password: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ],
        tenantCode: [
          { required: true, trigger: 'blur', message: this.$t('必填信息') }
        ],
        code: [{ required: true, trigger: 'change', message: this.$t('必填信息') }],
        verifyCode: [{ required: true, trigger: 'change', message: this.$t('必填信息') }]
      },
      loading: false,
      showDevice: false,
      deviceBtnTxt: '获取设备验证码',
      verifyType: 'phone',
      isVerify: false,
      curentDevice: '',
      phone: '',
      email: '',
      deviceBtnDisable: false,
      redirect: undefined,
      tenantCompanyInfo: {
        logo: undefined,
        name: undefined,
        width: undefined,
        height: undefined
      },
      excludes: {
        language: true,
        colorDepth: true,
        deviceMemory: true,
        pixelRatio: true,
        availableScreenResolution: true,
        timezoneOffset: true,
        timezone: true,
        sessionStorage: true,
        localStorage: true,
        indexedDb: true,
        addBehavior: true,
        openDatabase: true,
        cpuClass: true,
        doNotTrack: true,
        plugins: true,
        canvas: true,
        webglVendorAndRenderer: true,
        adBlock: true,
        hasLiedLanguages: true,
        hasLiedResolution: true,
        hasLiedOs: true,
        hasLiedBrowser: true,
        touchSupport: true,
        audio: false,
        enumerateDevices: true,
        hardwareConcurrency: true
      },
      timer: null,
      isCode: true
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {
    this.getCode()
    this.getCookie()
    // 查询是否多租户
    this.getTenant()
    // 获取租户logo和名称
    this.getTenantInfo()
    // 获取设备ID
    this.getDeviceId()
  },
  mounted() {
    this.$store.state.permission.leftActive = this.$store.state.permission.navActive = ''
    Cookies.remove('_nav_active_')
    Cookies.remove('_no-id_')
    Cookies.remove('_sider_bar_active_')
    Cookies.set('loadTimes', '0')

    // 绑定登录页回车键登录事件
    window.addEventListener('keydown', this.keyDown)
  },
   // 增加登录页回车键登录功能
  methods: {
    toOpen(href) {
      window.open(href, '_blank')
    },
    changeVerifyType(val) {
      this.verifyType = val
      this.curentDevice = this.verifyType === 'phone' ? this.phone : this.email
    },
    getDeviceId() {
      const options = Fingerprint.Options = {
        excludes: this.excludes
      }
      Fingerprint.get(options, components => {
        const values = components.map((component, index) => {
          if (index === 0) {
            return component.value.replace(/\bNetType\/\w+\b/, '')
          }
          return component.value
        })
        // 生成指纹
        const fingerNumber = Fingerprint.x64hash128(values.join(''), 31)
        this.loginForm.pcDeviceId = fingerNumber
      })
    },
    keyDown(e) {
      if (e.keyCode === 13) {
        this.handleLogin()
      }
    },
    chat() {
      if (this.$refs.contactUs?.visible !== undefined) {
        this.$refs.contactUs.visible = true
      }
    },
    toReset() {
      this.$router.push({ path: '/recoverpw' })
    },
    getCode() {
      if (this.loginFailNum >= 3) {
        getCodeImg().then(res => {
          this.codeUrl = 'data:image/gif;base64,' + res.datas.img
          this.loginForm.uuid = res.datas.uuid
        })
      }
    },
    verifySuccess() {
      this.isVerify = false
    },
    getCookie() {
      const username = Cookies.get('username')
      const password = Cookies.get('password')
      var tenantCode = Cookies.get('tenantCode')
      this.isCode = true
      if (this.$route.query?.code !== undefined) {
        this.isCode = false
        tenantCode = this.$route.query.code
      }

      var tenantCompanyInfo = window.localStorage.getItem('tenantCompanyInfo')
      if (tenantCompanyInfo) {
        try {
          this.tenantCompanyInfo = JSON.parse(tenantCompanyInfo)
        } catch (e) {
          console.log(e)
        }
      }

      this.loginForm = {
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        tenantCode: tenantCode === undefined ? undefined : tenantCode
      }
      if (username === undefined) {
        this.rememberMe = false
      }
    },
    // 获取是否展示验证码
    captchaImageShow() {
      if (this.loginForm.username !== undefined && this.loginForm.username !== '') {
        if (this.tenant === 'true') {
          if (!this.loginForm.tenantCode || this.loginForm.tenantCode === '') {
            return false
          }
        }
        captchaImageShow(this.loginForm.username, this.loginForm.tenantCode).then(res => {
          if (res.data) {
            this.loginFailNum = 3
            this.getCode()
          }
        })
      }
    },
    /**
     * 获取是不是多租户模式
     */
    getTenant() {
      this.formLoadIng = true
      getTenant().then(res => {
        if (res !== undefined) {
          this.tenant = res.data
        }
      })
    },
    // 获取当前租户的logo和名称
    getTenantInfo(tenantCode) {
      // 从url中获取租户code
      if (tenantCode === undefined) {
        tenantCode = this.$route.query.tenantCode
      }
      if (tenantCode !== undefined) {
        this.loginForm.tenantCode = tenantCode
      }
      getTenantInfo(this.loginForm.tenantCode).then(res => {
        if (res.data !== null) {
          this.tenantCompanyInfo.logo = res.data.productLogo
          this.tenantCompanyInfo.name = res.data.productName
          this.tenantCompanyInfo.width = res.data.productLogoWidth
          this.tenantCompanyInfo.height = res.data.productLogoHeight
        } else {
          this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        }
        console.log(JSON.stringify(this.tenantCompanyInfo))
        window.localStorage.setItem('tenantCompanyInfo', JSON.stringify(this.tenantCompanyInfo))
        this.formLoadIng = false
      }).catch(() => {
        this.tenantCompanyInfo = { logo: undefined, name: undefined, width: undefined, height: undefined }
        this.formLoadIng = false
      })
    },
    // 更新失败次数
    addLoginFailNum() {
      this.loginFailNum++
    },
    getLanguage() {
      getLanguage(undefined, this.loginForm.tenantCode).then(response => {
        var localStorage = window.localStorage.getItem('language')
        if (localStorage === undefined || localStorage === null || localStorage === 'null') {
          localStorage = 'zh_cn'
        }
        this.$i18n.vm.messages[localStorage] = response.languageData
        // 修改国际化词条
        window.localStorage.setItem('language_' + localStorage, JSON.stringify(response.languageData))
        window.localStorage.setItem('language', localStorage)
        this.$i18n.locale = localStorage
      })
      this.getTenantInfo(this.loginForm.tenantCode)
    },
    getCheckDeviceCode(isSend = true) {
      var num = 60
      this.deviceBtnDisable = true
      this.timer = setInterval(() => {
        this.deviceBtnTxt = num < 10 ? '0' + num + 's后重新获取' : num + 's后重新获取'
        if (num <= 0) {
          this.deviceBtnTxt = '重新获取'
          this.deviceBtnDisable = false
          clearInterval(this.timer)
        }
        num--
      }, 1000)
      if (isSend) {
        sendDeviceCode(this.loginForm.username, this.verifyType).then(res => {
          this.$message.success(res.datas.msg)
        }).catch(() => {
          clearInterval(this.timer)
          this.deviceBtnDisable = false
          this.deviceBtnTxt = '重新获取'
        })
      }
    },
    handleLogin() {
      console.log('登录')
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.rememberMe) {
            Cookies.set('username', this.loginForm.username, { expires: 30 })
            Cookies.set('password', encrypt(this.loginForm.password), { expires: 30 })
            Cookies.set('tenantCode', this.loginForm.tenantCode, { expires: 30 })
          } else {
            Cookies.remove('username')
            Cookies.remove('password')
            Cookies.remove('tenantCode')
          }
          // 重新登陆获取用户的机构编码
          window.localStorage.setItem('tenantCode', this.loginForm.tenantCode)

          this.$store
            .dispatch('Login', this.loginForm)
            .then((res) => {
                if (res && res.msg) {
                  this.showDevice = true
                  this.loading = false
                  this.phone = res.phoneNumber
                  this.email = res.email
                  this.curentDevice = this.verifyType === 'phone' ? this.phone : this.email
                  this.isVerify = true
                  return
                } else {
                  this.showDevice = false
                }
                 // 是否开启天眼查
                  getConfigKey('enable_tyc').then(res => {
                       window.localStorage.setItem('enableTyc', res.msg)
                   }).catch(() => {
                       window.localStorage.removeItem('enableTyc')
                   })
                this.$router.push({ path: '/', name: '首页', params: { once: 1 }})
                // this.$store.state.permission.leftActive = this.$store.state.permission.navActive = ''
            })
            .catch((err) => {
              if (err === '验证码已失效') {
                this.loading = false
                this.loginFailNum = 3
                this.getCode()
              } else if (err === '设备验证码错误') {
                this.loading = false
              } else {
                this.loading = false
                // 更新登录失败次数
                this.addLoginFailNum()
                this.getCode()
              }
            })
        }
      })
    },
    onRegister() {
      this.$router.push({ path: '/register' })
    }

  }
}
</script>
<style scoped lang="scss">
.pub-icon{
  position: fixed;
  right: 20px;
  top: 20px;
  display: flex;
  align-items: center;
  font-weight: bold;
  background-image: linear-gradient(0deg, #04c5dc, #069cf3);
  background-clip:text;
  -webkit-background-clip:text;
  color: transparent;
  .pub{
    display: inline-block;
    width: 25px;
    height: 25px;
    background-size: cover;
    background-image: url();
  }
}
.login .el-login-footer{
  height: unset!important;
  line-height: unset!important;
  bottom: 5px!important;
  .links{
    margin: 0;
    margin-bottom: 5px;
    a{
      text-decoration: underline;
    }
  }
}
/deep/.input-with-select{
  .el-input__inner{
    border-color: #DCDFE6  !important;
  }
}
/deep/.input-with-select .el-input-group__prepend {
  background-color: #fff;
  width: 20px;
  .el-input__prefix{
    text-indent: .5em;
  }
  .el-input__inner{
    border-color: #DCDFE6  !important;
  }
}
.cursor{
  cursor: pointer;
}
.pswRow .right{
  font-size: 14px;
}
</style>
